<template>
    <div>
        <el-tabs type="border-card" class="xx-tabs">
            <el-tab-pane label="正在下载">
                <xx-table
                :tableData="tableData"
                :showDefalutButton="false"
                :showDefalutPagination="false"
                :showDefalutExpand="false"
                :showDefalutTools="false">
                    <template v-slot:item="slotProps">
                        <div class="xx-list-item">
                            <div style="height:25px;width:25px;background-size:cover;margin-right:10px;" :class="`file type-${slotProps.item.itemInfo.suffix}`"></div>
                            <div class="text">{{slotProps.item.itemInfo.name}}</div>
                        </div>
                    </template>
                    <template v-slot:size="slotProps">
                        <div class="xx-list-item">
                            <div class="text">{{slotProps.item.size}}</div>
                        </div>
                    </template>
                    <template v-slot:speed="slotProps">
                        <div class="xx-list-item">
                            <div class="text">{{slotProps.item.speed}}</div>
                        </div>
                    </template>
                    <template v-slot:progress="slotProps">
                        <el-progress :percentage="slotProps.item.progress"></el-progress>
                    </template>
                    <template v-slot:tools="slotProps">
                        <div class="xx-list-item">
                            <el-popover
                            placement="right"
                            trigger="click">
                            <div class="xx-btns">
                                <el-button @click="openFile(slotProps.item.path)" size="mini">打开文件</el-button>
                                <el-button @click="openDir(slotProps.item.path)" size="mini">打开文件夹</el-button>
                                <el-button size="mini">属性</el-button>
                            </div>
                            <el-button slot="reference" size="mini" icon="el-icon-more-outline" circle></el-button>
                            </el-popover>

                        </div>
                    </template>
                </xx-table>
            </el-tab-pane>
            <el-tab-pane label="正在上传">正在上传</el-tab-pane>
            <el-tab-pane label="传输完成(5)">传输完成</el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import API from '../../../api'
import XxTable from '../../../components/XxTable.vue'
import StringFormatter from '../../../utils/StringFormatter'
import { remote } from 'electron'
import path from 'path'
import File from '../../../utils/file'
import fs from 'fs'
export default {
    components: { XxTable },
    data() {
        return {
            tableData: {
                pages: 1,
                header: [
                    {
                        label: '项目',
                        width: '300px',
                        prop: 'item',
                        type: 'no-editslot'
                    },
                    {
                        label: '大小',
                        width: '',
                        prop: 'size',
                        type: 'no-editslot'
                    },
                    {
                        label: '速度',
                        width: '',
                        prop: 'speed',
                        type: 'no-editslot'
                    },
                    {
                        label: '进度',
                        width: '200px',
                        prop: 'progress',
                        type: 'no-editslot'
                    },
                    {
                        label: '操作',
                        width: '',
                        prop: 'tools',
                        type: 'no-editslot'
                    }
                ],
                data: []
            }
        }
    },
    mounted() {
        this.readDownloadList()
        console.log('下载列表初始化')
        this.$root.$on('download', (item, path) => { // 监听事件，这里$root很重要，不懂去官网介绍
            this.download(item, path)
        })
    },
    beforeDestroy() {
        this.$root.$off('download')
    },
    methods: {
        openFile(path) {
            remote.shell.openPath(path)
        },
        openDir(path) {
            remote.shell.showItemInFolder(path)
        },
        async download(item, path) {
            if (path == undefined) {
                this.$message('您没有指定下载位置,无法开始下载')
                return
            }
            this.tableData.data.unshift({
                itemInfo: item,
                speed: '-',
                time: '-',
                progress: 0
            })
            const index = 0
            const downloadItem = this.tableData.data[index]
            downloadItem.path = path + `\\${item.name}`
            File.downloadFile({
                remoteFile: 'https://disk.xiaotao2333.top:344/api/' + encodeURI(API.resource.downloadFileByMD5(item.md5, item.name).url),
                localFile: path + `\\${item.name}`,
                onProgress: (received, total, length) => {
                    const curr = new Date()
                    if (downloadItem.lastRecord == null) {
                        downloadItem.lastRecord = {
                            received: received,
                            date: curr
                        }
                    }
                    var percentage = (received * 100) / total
                    downloadItem.progress = parseInt(percentage)
                    downloadItem.size = `${StringFormatter.formatSizeString(received)}/${StringFormatter.formatSizeString(total)}`
                    if (curr - downloadItem.lastRecord.date > 1000) {
                        downloadItem.speed = `${StringFormatter.formatSizeString(received - downloadItem.lastRecord.received)}/s`
                        downloadItem.lastRecord = {
                            received: received,
                            date: curr
                        }
                    }
                }
            }).then(() => {
                downloadItem.size = downloadItem.size.split('/')[0]
                downloadItem.speed = '-'
                this.saveDownloadList()
            })
        },
        saveDownloadList() {
            try {
                const filePath = path.join(remote.app.getPath('userData'), 'saltedfishcloud-downloadList.json')
                fs.writeFileSync(filePath, JSON.stringify(this.tableData.data))
                // 文件写入成功。
            } catch (err) {
                console.error(err)
            }
        },
        readDownloadList() {
            // 读取配置文件，变量config的类型是Object类型
            let data = null
            const filePath = path.join(remote.app.getPath('userData'), 'saltedfishcloud-downloadList.json')
            console.log(filePath)
            try {
                data = JSON.parse(fs.readFileSync(filePath).toString())
                this.tableData.data = data
                console.log(this.$route.params.logout)
                if (this.$route.params.logout) {
                    return
                }
                this.login()
            } catch (err) {
                console.log('没有默认账号密码。')
            }
        }
    }
}
</script>

<style lang="less" scoped>
.xx-tabs {
    height: calc(100vh - 80px);
}
.xx-list-item {
    display: flex;
    flex-direction: row;
    .text {
        font-size: 12px;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}
.xx-btns {
    display: flex;
    flex-direction: column;
    justify-content: center;
    button {
        margin: 0px;
    }
}
</style>
